﻿#region  文件信息
// ---------------------------------------------------------------------------------------
// <copyright file="UserAuthorizeAttribute.cs" company="">
// 作者：李帅伦
// </copyright>
// <summary>
// 类型简介：
// 类型详细：UserAuthorizeAttribute.cs
// 创建时间：2014-10-30 16:36
// 修改时间：2014-10-30 16:36
// </summary>
// ---------------------------------------------------------------------------------------
#endregion
namespace OneAdmin.Filters
{
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Security;

    public class UserAuthorizeAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// 需要的权限
        /// </summary>
        public string[] RoleStrings { get; set; }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="roles"></param>
        public UserAuthorizeAttribute(params string[] roles)
        {
            this.RoleStrings = roles;
        }
        /// <summary>
        /// 需要登录判断
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext.User != null && httpContext.User.Identity.IsAuthenticated)
            {
                return IsAuthorize();

            }
            else
            {

                return false;
            }
        }

        /// <summary>
        /// 判断权限方法
        /// </summary>
        /// <returns></returns>
        protected virtual bool IsAuthorize()
        {
            //判断当前用户身份验证的方式是否为Forms身份验证方式
            var userIdent = (FormsIdentity)HttpContext.Current.User.Identity;
            var userData = userIdent.Ticket.UserData.Split(',');

            var b = this.RoleStrings.All(x => userData.Any(y => y == x));
            return b;
        } 
    }
}